
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;

public class ShmReader {

    private static FileChannel inChannel = null;
    private static int ELEM_SIZE = 50;
    private static int ELEM_COUNT = 100000;
    public static void sayHello() {
        System.out.println("Hello, Java world! ");
    }

    private static int getRelativeOffset(int index) {
        if ((index <ELEM_COUNT )&& (index>=0) ) {
            return (ELEM_SIZE * index);
        }
        return -1;
    }

    public static String getValue(int index) {
        String str = null;
        int nRelativeOffset = getRelativeOffset(index);
        if (nRelativeOffset >= 0) {
            try {
                inChannel.position(nRelativeOffset);
                ByteBuffer buf = ByteBuffer.allocate(ELEM_SIZE);
                int bytesRead = inChannel.read(buf);
                System.out.println("bytesRead " + bytesRead + " nRelativeOffset " + nRelativeOffset + " index " + index);
                if (buf.capacity() == bytesRead) {
                    str = new String(buf.array(), "ASCII");
                    System.out.println("Reading " + str);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return str;
    }

    public static boolean init(String path, int nElemSize, int nElemCount) {
        boolean bStat = false;
        ELEM_SIZE = nElemSize;
        ELEM_COUNT = nElemCount;
        RandomAccessFile aFile = null;
        try {
            aFile = new RandomAccessFile(path, "r");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        inChannel = aFile.getChannel();
        bStat = true;
        System.out.println("Opened file " + path + " for reading.");
        return bStat;
    }

    public static void main(String[] args) {
        boolean bStat = init("mapfile.bin",50,100000 );
        if (false == bStat) {
            return;
        }
        for (int index = 0; index < 10; index++) {
		//for (int index = 0; index < 100000; index++) {
            String str = getValue(index);
            System.out.println("Buf at " + index + " " + str);
        }
    }
}
